if (Meteor.isServer) { 
  Meteor.publish('sale_orders', function () {
    if (!this.userId) return;
    var conditions={'company_id':Meteor.users.findOne(this.userId).company_id};
    // 店长权限 ，发布店铺范围的订单
    if (Roles.userIsInRole(this.userId, ['storeOrdersPub'])) {
      var user = Meteor.users.findOne(this.userId,{_id:0,'company_id':1,'profile.departments':1});
      var storeId = user.profile.departments[user.profile.departments.length-1]._id;
      conditions['store._id']=storeId;
    // 销售员权限 ，发布销售员个人的订单
    }else if(Roles.userIsInRole(this.userId, ['salesManOrdersPub'])){
      conditions['seller._id']=this.userId;
    }
    return SaleOrders.find(conditions);
  });
}

Meteor.methods({
/**
 * 创建销售单
 */
  createSaleOrder:function(newSaleOrder){
    checkLogin(this.userId);
    checkPermission(this.userId,['createSaleOrder']);

    if (!newSaleOrder.list || !newSaleOrder.amount) {
      throw new Meteor.Error(10080,'没有选择商品。');
    }
    var user = Meteor.users.findOne(this.userId,{_id:0,'company_id':1,'profile.departments':1});

    newSaleOrder.company_id = user.company_id;
    newSaleOrder.date = moment().toDate();
    newSaleOrder.state_history=[{
    	operation:'开单',
    	operater:{
	    	'_id':this.userId,
	    	'name':user.profile.name
    	},
    	date:moment().toDate()
    }];

    newSaleOrder.seller = {
    	'_id':this.userId,
      'name':user.profile.name
    };
    // TODO
    var storeId="", whId="";
    user.profile.departments.forEach(function(dept){
      if(dept.type=="门店"){
        storeId = dept._id;
      }
      if(dept.type=="柜组"){
        whId = dept._id;
      }
    });
    newSaleOrder.store = {
    	"_id":storeId,
    	"name":"南山店"
    }
    newSaleOrder.warehouse = {
    	"_id":whId,
    	"name":"柜组1"
    }

    newSaleOrder.state = '待付款';
    try {
      newSOId = SaleOrders.insert(newSaleOrder);
    } catch (e) {
      throw e;
    }
    return newSOId;
  },

  updateSOState:function(stateData){
    checkLogin(this.userId);
    var user = Meteor.users.findOne(this.userId,{_id:0,'company_id':1,'profile.pmsn_group':1});
    var theOrder = SaleOrders.findOne(stateData.order_id);
    try {
      theSOId = SaleOrders.update(stateData.order_id, {$set:{state:stateData.state.operation}, $push: { state_history: stateData.state } });
    } catch (e) {
      throw e;
    }
    return theSOId;
  }
});


if (SaleOrders.find().count() === 0) {
  SaleOrders.insert({
    "price_type" : "零售",
    "total_count" : 2,
    "amount" : 12400,
    "list" : [{
      "catalog" : "手机",
      "barcode" : "9652524125412",
      "properties" : {
        "brand" : { "name" : "品牌", "value" : "苹果", "logo" : "apple" },
        "model" : { "name" : "型号", "value" : "iphone 6 plus(A1530)" },
        "color" : { "name" : "颜色", "value" : "白色" },
        "netType" : { "name" : "网络", "value" : "移动4G" },
        "version" : { "name" : "版本", "value" : "国行" },
        "memoInside" : { "name" : "机身内存", "value" : "64G" }
      }, "thumb" : "img/1.jpg",
      "pics" : [ ],
      "single_barcode" : "6920002010232",
      "cost_price_default" : 5188,
      "sale_price" : 6200,
      "min_sale_price" : 5500,
      "company_id" : "1",
      "_id" : "3Swi2B69pafEWuhzA",
      "final_price" : 6200,
      "count" : 2
    }],
    "customer" : { "birthday" : null },
    "company_id" : "1",
    "date" : moment([2016,10,29,15,12,54]).toDate(),
    "state_history" : [ {
      "operation" : "开单",
      "operater" : { "_id" : "3", "name" : "玳瑁" },
      "date" :  moment([2016,10,29,15,12,54]).toDate()
    }],
    "seller" : { "_id" : "3", "name" : "玳瑁" },
    "state" : "待付款",
    "store" : {
        "_id":"3",
        "name":"南山店"
      },
    "warehouse" : {
        "_id":"12",
        "name":"柜组1"
      }
  });

  SaleOrders.insert({
    "price_type" : "零售",
    "total_count" : 2,
    "amount" : 8300,
    "list" : [{
      "catalog" : "手机",
      "barcode" : "9652524125412",
      "properties" : {
        "brand" : { "name" : "品牌", "value" : "苹果", "logo" : "apple" },
        "model" : { "name" : "型号", "value" : "iphone 6 plus(A1530)" },
        "color" : { "name" : "颜色", "value" : "白色" },
        "netType" : { "name" : "网络", "value" : "移动4G" },
        "version" : { "name" : "版本", "value" : "国行" },
        "memoInside" : { "name" : "机身内存", "value" : "64G" }
      }, "thumb" : "img/1.jpg",
      "pics" : [ ],
      "single_barcode" : "6920002010232",
      "cost_price_default" : 5188,
      "sale_price" : 6200,
      "min_sale_price" : 5500,
      "company_id" : "1",
      "_id" : "3Swi2B69pafEWuhzA",
      "final_price" : 6200, "count" : 1
    }, {
      "catalog" : "手机",
      "barcode" : "2524123456125",
      "properties" : { "brand" : { "name" : "品牌", "value" : "小米", "logo" : "xiaomi" },
        "model" : { "name" : "型号", "value" : "M1530" },
        "color" : { "name" : "颜色", "value" : "白色" },
        "netType" : { "name" : "网络", "value" : " 移动4G" },
        "version" : { "name" : "版本", "value" : "国行" },
        "memoInside" : { "name" : "机身内存", "value" : "16G" }
      }, "thumb" : "img/3.jpg",
      "pics" : [ ],
      "single_barcode" : "6920002014367",
      "cost_price_default" : 1200,
      "sale_price" : 2100,
      "min_sale_price" : 1800,
      "company_id" : "1", "_id" : "bPwvn8hjFBb3kuzDX", "final_price" : 2100, "count" : 1 } ],
      "customer" : { "name" : "xxx", "phone" : "12344343324", "sex" : "男",
      "birthday" : moment([1985,0,10]).toDate() },
      "company_id" : "1",
      "date" : moment([2016,10,28,8,12,54]).toDate(),
      "state_history" : [ {
        "operation" : "开单",
        "operater" : { "_id" : "3", "name" : "玳瑁" },
        "date" : moment([2016,10,28,8,12,54]).toDate()
      }],
      "seller" : { "_id" : "3", "name" : "玳瑁" },
      "state" : "待付款" ,
      "store" : {
        "_id":"3",
        "name":"南山店"
      },
      "warehouse" : {
        "_id":"12",
        "name":"柜组1"
      }
  });

  SaleOrders.insert({
    "price_type" : "零售", "total_count" : 2, "amount" : 5600,
    "list" : [{
      "catalog" : "手机", "barcode" : "2524123456125",
      "properties" : {
        "brand" : { "name" : "品牌", "value" : "华为", "logo" : "huawei" },
        "model" : { "name" : "型号", "value" : "荣耀8(R1530)" },
        "color" : { "name" : "颜色", "value" : "白色" },
        "netType" : { "name" : "网络", "value" : "移动4G" },
        "version" : { "name" : "版本", "value" : "国行" },
        "memoInside" : { "name" : "机身内存", "value" : "8G" },
        "memoCard" : { "name" : "内存卡", "value" : "64G" }
      },
      "thumb" : "img/4.jpg", "pics" : [ ], "single_barcode" : "1011001013141",
      "cost_price_default" : 2800, "sale_price" : 3600, "min_sale_price" : 3100,
      "company_id" : "1",
      "_id" : "De4tADg4DTncEsxan",
      "final_price" : 3500,
      "count" : 1
    }, {
      "catalog" : "手机", "barcode" : "2524123456220",
      "properties" : {
        "brand" : { "name" : "品牌", "value" : "魅族", "logo" : "meizu" },
        "model" : { "name" : "型 号", "value" : "魅族 MX5(M1530)" },
        "color" : { "name" : "颜色", "value" : "白色" },
        "netType" : { "name" : "网络", "value" : "移动3G" },
        "version" : { "name" : "版本", "value" : "国行" },
        "memoInside" : { "name" : "机 身内存", "value" : "32G" } },
        "thumb" : "img/2.jpg", "pics" : [ ], "single_barcode" : "6920002010452",
        "cost_price_default" : 1500, "sale_price" : 2700, "min_sale_price" : 2100,
        "company_id" : "1",
        "_id" : "dcFS7f8jb4AFt4pet",
        "final_price" : 2100, "count" : 1
      } ],
      "customer" : { "name" : "ccc", "phone" : "13566565532", "sex" : "男",
      "birthday" : moment([1990,5,8]).toDate() }, "company_id" : "1",
      "date" : moment([2016,10,27,10,20,54]).toDate(),
      "state_history" : [ {
        "operation" : "开单",
        "operater" : { "_id" : "3", "name" : "玳瑁" },
        "date" : moment([2016,10,27,10,20,54]).toDate() } ],
      "seller" : { "_id" : "3", "name" : "玳瑁" },
      "state" : "待出库" ,
      "store" : {
        "_id":"3",
        "name":"南山店"
      },
      "warehouse" : {
        "_id":"12",
        "name":"柜组1"
      }
  });

  SaleOrders.insert({
    "price_type" : "零售", "total_count" : 3, "amount" : 6000,
    "list" : [{
      "catalog" : "手机",
      "barcode" : "2524123456125",
      "properties" : {
        "brand" : { "name" : "品牌", "value" : "小米", "logo" : "xiaomi" },
        "model" : { "name" : "型号", "value" : "M1530" },
        "color" : { "name" : "颜色", "value" : "白色" },
        "netType" : { "name" : "网络", "value" : "移动4G" },
        "version" : { "name" : "版本", "value" : "国行" },
        "memoInside" : { "name" : "机身内存", "value" : "16G" }
      },
      "thumb" : "img/3.jpg", "pics" : [ ], "single_barcode" : "6920002014367",
      "cost_price_default" : 1200,
      "sale_price" : 2100,
      "min_sale_price" : 1800,
      "company_id" : "1",
      "_id" : "bPwvn8hjFBb3kuzDX",
      "final_price" : 2000,
      "count" : 3
    }],
    "customer" : {
      "name" : "mm",
      "phone" : "13613544251",
      "sex" : "女",
      "birthday" : moment([1995,5,8]).toDate()
    },
    "company_id" : "1",
    "date" : moment([2016,10,20,8,20,54]).toDate(),
    "state_history" : [{
      "operation" : " 开单",
      "operater" : { "_id" : "3", "name" : "玳瑁" },
      "date" :  moment([2016,10,20,8,20,54]).toDate() }
    ],
    "seller" : { "_id" : "3", "name" : "玳瑁" },
    "state" : "已完成",
    "store" : {
      "_id":"3",
      "name":"南山店"
    },
    "warehouse" : {
      "_id":"12",
      "name":"柜组1"
    }
  });

}
